package com.cmes.core.context;

import com.cmes.core.utils.StringPool;
import com.cmes.core.utils.StringUtils;
import org.slf4j.MDC;

/**
 * traceId 容器
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
public class TraceContextHolder {

    private static final ThreadLocal<String> LOCAL = new InheritableThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return StringPool.EMPTY;
        }
    };

    public static void setTraceId(String traceId) {
        MDC.put("traceId", traceId);
        LOCAL.set(traceId);
    }

    public static void clearTraceId() {
        MDC.clear();
        LOCAL.remove();
    }

    public static String getTraceId() {
        return StringUtils.defaultIfEmpty(LOCAL.get(), StringPool.EMPTY);
    }

}
